package com.briup.es.interceptor;

import com.briup.es.auth.SecurityUserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在浏览器请求跨域前会发送一个 Options请求，用于查询服务器是否支持跨域；
        // Options请求不会携带任何参数，所以校验token，直接放行即可
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }

        // 从请求头中获取用户id
        String userId = request.getHeader("X-User-Id");
        // 将userId放入到SecurityUserContext中
        if (StringUtils.hasText(userId)){
            SecurityUserContext.setCurrentUserId(Integer.parseInt(userId));
        }

        // 做完以上操作后，直接放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除本请求在 上下文中 存储的用户数据
        SecurityUserContext.clear();
    }
}
